package com.jf.ajax.dao;

import com.jf.ajax.utils.JDBCUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description:BasicDao开发
 * User:22954
 * Date:2024-09-13
 * Time:20:39
 */
public class BasicDAO<T> {
    private final QueryRunner qr = new QueryRunner();

    /**
     * 查询多条结果
     * @param sql 待执行的sql语句
     * @param clazz 需返回的类的Class对象
     * @param params 参数列表
     * @return 查询的结果集合
     */
    public List<T> queryMulti(String sql, Class<T> clazz, Object... params) {
        Connection connection = null;
        connection = JDBCUtilsByDruid.getConnection();
        try {
            return qr.query(connection, sql, new BeanListHandler<T>(clazz), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtilsByDruid.release(connection);
        }
    }

    /**
     * 查询单条结果
     * @param sql 待执行的sql语句
     * @param clazz 需返回的类的Class对象
     * @param params 参数列表
     * @return 查询的单行结果
     */
    public T querySingle(String sql, Class<T> clazz, Object... params) {
        Connection connection = null;
        connection = JDBCUtilsByDruid.getConnection();
        try {
            return qr.query(connection, sql, new BeanHandler<T>(clazz), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtilsByDruid.release(connection);
        }
    }

    /**
     * 查询单行单列结果
     * @param sql 待执行的sql语句
     * @param params 参数列表
     * @return 查询到的单行单列结果
     */
    public Object queryScalar(String sql, Object... params) {
        Connection connection = null;
        connection = JDBCUtilsByDruid.getConnection();
        try {
            return qr.query(connection, sql, new ScalarHandler<>(), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtilsByDruid.release(connection);
        }
    }

    /**
     * 通用DML方法
     * @param sql 待执行的sql语句
     * @param params 参数列表
     * @return 受影响的行数
     */
    public int update(String sql, Object... params) {
        Connection connection = null;
        connection = JDBCUtilsByDruid.getConnection();
        try {
            return qr.update(connection, sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtilsByDruid.release(connection);
        }
    }
}
